

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 参考资料 MOOC 运行环境  windows10 JDK8 IDEA 2021.1专业版 Spring 5.0.5  一、Spring MVC 学习任务：  完成Spring MVC 环境的搭建，并实现视图层 View 与 控制器 Controller 之间的参数传递 超市系统的登录功能  1.1 相关概念1. SpringMVCSpring MVC是Spring框架提供的一个 M">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringMVC 笔记1 框架特点 体系架构 执行流程 参数处理 传递">
<meta property="og:url" content="http://example.com/2022/01/23/SpringMVC%20%E7%AC%94%E8%AE%B01%20%E6%A1%86%E6%9E%B6%E7%89%B9%E7%82%B9%20_%20%E4%BD%93%E7%B3%BB%E6%9E%B6%E6%9E%84%20_%20%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B%20_%20%E5%8F%82%E6%95%B0%E5%A4%84%E7%90%86%E3%80%81%E4%BC%A0%E9%80%92/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 参考资料 MOOC 运行环境  windows10 JDK8 IDEA 2021.1专业版 Spring 5.0.5  一、Spring MVC 学习任务：  完成Spring MVC 环境的搭建，并实现视图层 View 与 控制器 Controller 之间的参数传递 超市系统的登录功能  1.1 相关概念1. SpringMVCSpring MVC是Spring框架提供的一个 M">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/b833aa01e75447679cf322c8a4c7d1f0.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2920a0b88206497e8f5928ddcb44ac7e.png#pic_center">
<meta property="article:published_time" content="2022-01-23T13:14:48.000Z">
<meta property="article:modified_time" content="2022-08-22T15:48:58.130Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="SpringMVC">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/b833aa01e75447679cf322c8a4c7d1f0.png#pic_center">
  
  
  
  <title>SpringMVC 笔记1 框架特点 体系架构 执行流程 参数处理 传递 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="SpringMVC 笔记1 框架特点 体系架构 执行流程 参数处理 传递"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-01-23 21:14" pubdate>
          2022年1月23日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          51 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">SpringMVC 笔记1 框架特点 体系架构 执行流程 参数处理 传递</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><hr>
<p><a target="_blank" rel="noopener" href="http://spoc.wzu.edu.cn/study/initplay/791671.mooc">MOOC</a></p>
<h1 id="运行环境"><a href="#运行环境" class="headerlink" title="运行环境"></a>运行环境</h1><hr>
<ul>
<li>windows10</li>
<li>JDK8</li>
<li>IDEA 2021.1专业版</li>
<li>Spring 5.0.5</li>
</ul>
<h1 id="一、Spring-MVC"><a href="#一、Spring-MVC" class="headerlink" title="一、Spring MVC"></a>一、Spring MVC</h1><hr>
<p>学习任务：</p>
<ul>
<li>完成Spring MVC 环境的搭建，并实现视图层 View 与 控制器 Controller 之间的参数传递</li>
<li>超市系统的登录功能</li>
</ul>
<h2 id="1-1-相关概念"><a href="#1-1-相关概念" class="headerlink" title="1.1 相关概念"></a>1.1 相关概念</h2><p><strong>1. SpringMVC</strong><br>Spring MVC是Spring框架提供的一个 MVC 设计模式的优秀web开发框架，本质上加了@Controller对象，SpringMVC充当控制器（Controller）来建立模型与视图的交互</p>
<p><strong>2.DispatcherServlet **<br>DispatcherServlet，即中央调度器，是web开发底层Servlet类的子类，它负责</strong>接收用户的所有请求** ，用户把请求提交给 DispatherServlet，之后 DispatherServlet把请求转发给Controller对象，最后是由Controller对象处理请求</p>
<p>DispatcherServlet 是SpringMVC中最核心的类，通常在web.xml里配置</p>
<p><strong>3.Handler</strong></p>
<p>处理器，对应MVC中的C，Controller层</p>
<ul>
<li>类型：Obejct</li>
<li>作用：处理实际请求</li>
<li>标注了@RequestMapping的所有方法都可以看做是一个 Handler</li>
</ul>
<p><strong>4.ModelAndView</strong><br>逻辑视图名 + 视图解析器（找到真实视图）</p>
<p><strong>5.Model</strong></p>
<ul>
<li>类型：Map</li>
<li>常用方法：添加模型数据</li>
<li>处理方法的传入参数为Model类型</li>
<li>页面也可以直接根据model的key取值</li>
</ul>
<p><strong>6.View</strong><br>模型对象，一般为业务层交互后返回的数据</p>
<p><strong>7.InternalResourceViewResolver</strong><br>视图解析器，重要的有prefix前缀和suffix后缀两个参数</p>
<h2 id="1-2-SpringMVC框架的特点"><a href="#1-2-SpringMVC框架的特点" class="headerlink" title="1.2 SpringMVC框架的特点"></a>1.2 SpringMVC框架的特点</h2><ul>
<li>清晰的角色划分</li>
<li>灵活的配置功能</li>
<li>提供了大量的控制器接口和实现类</li>
<li>真正做到与View层的实现无关（JSP、Velocity、Xslt等）</li>
<li>国际化支持</li>
<li>面向接口编程</li>
<li>Spring提供了Web应用开发的一整套流程，不仅仅是MVC，他们之间都可以很方便的结合在一起</li>
</ul>
<h2 id="1-3-SpringMVC-体系架构与执行流程"><a href="#1-3-SpringMVC-体系架构与执行流程" class="headerlink" title="1.3 SpringMVC 体系架构与执行流程"></a>1.3 SpringMVC 体系架构与执行流程</h2><h2 id="1-3-执行流程示意图"><a href="#1-3-执行流程示意图" class="headerlink" title="1.3 执行流程示意图"></a>1.3 执行流程示意图</h2><p><img src="https://img-blog.csdnimg.cn/b833aa01e75447679cf322c8a4c7d1f0.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="1-4-执行流程分析"><a href="#1-4-执行流程分析" class="headerlink" title="1.4 执行流程分析"></a>1.4 执行流程分析</h2><ol>
<li>浏览器提交请求到中央调度器 <code>DispatcherServlet</code></li>
<li>中央调度器<code>DispatcherServlet</code>直接将请求转发给处理器映射器<code>HandleMapping</code></li>
<li>处理器映射器<code>HandleMapping</code>会根据请求，找到该请求的处理器<code>Handle</code>，并将其封装为处理器执行链后返回给中央调度器<code>DispatcherServlet</code></li>
<li>中央调度器<code>DispatcherServlet</code>根据处理器执行链中的处理器Handle，找到能够执行该处理器的处理器适配器<code>HandleAdapter</code></li>
<li>处理器适配器<code>HandleAdapter</code>调用执行控制器<code>Controller</code></li>
<li>控制器<code>Controller</code>将处理结果以及要跳转的视图封装到一个对象 <code>ModleAndView</code>中，并将其返回给处理器适配器<code>HandleAdapter</code></li>
<li>处理器适配器<code>HandlerAdapter</code> 直接将结果返回给中央调度器 <code>DispatcherServlet</code></li>
<li>中央调度器 <code>DispatcherServlet </code>调用视图解析器<code>ViewResolver</code>，将<code>ModelAndView</code>中的视图名称封装为视图对象View</li>
<li>视图解析器<code>ViewResolver</code> 将封装了的视图对象<code>View</code>返回给中央调度器 <code>DispatcherServlet</code></li>
<li>中央调度器<code>DispatcherServlet</code> 调用视图对象<code>View</code>，让其自己进行渲染，即进行数据填充，形成影响对象</li>
<li>中央调度器<code>DispatcherServlet</code>响应浏览器</li>
</ol>
<h2 id="1-5-SpringMVC-请求处理流程"><a href="#1-5-SpringMVC-请求处理流程" class="headerlink" title="1.5 SpringMVC 请求处理流程"></a>1.5 SpringMVC 请求处理流程</h2><p><img src="https://img-blog.csdnimg.cn/2920a0b88206497e8f5928ddcb44ac7e.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="1-6-源代码分析"><a href="#1-6-源代码分析" class="headerlink" title="1.6 源代码分析"></a>1.6 源代码分析</h2><ul>
<li>Tomcat启动，创建容器的过程<br>通过 load-on-start 标签指定，创建 DispatcherServlet 对象，该类是HttpServlet的子类，在创建时候会执行 init()方法</li>
<li>在DispatcherServlet对象的init()方法中</li>
</ul>
<ol>
<li>创建容器，读取配置文件：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">WebApplicationContext</span> <span class="hljs-variable">ctx</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ClassPathXmlApplicationContext</span>(<span class="hljs-string">&quot;springmvc.xml&quot;</span>);<br></code></pre></td></tr></table></figure></li>
<li>把容器对象放到ServletContext中<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">getServletContext().setAttribute(key, ctx);<br></code></pre></td></tr></table></figure>
上面创建容器的作用： 创建@Controller注解所在的类的对象，创建 MyController对象，把这个对象放到springmvc的容器中，容器是map，类似于 &#96;map.put(“myController”, MyController对象)</li>
</ol>
<h1 id="二、SpringMVC的参数处理"><a href="#二、SpringMVC的参数处理" class="headerlink" title="二、SpringMVC的参数处理"></a>二、SpringMVC的参数处理</h1><hr>
<h2 id="2-1-请求数据"><a href="#2-1-请求数据" class="headerlink" title="2.1 请求数据"></a>2.1 请求数据</h2><p>请求数据有三种形式：Get请求、Post请求和文件请求</p>
<p>请求方式与提交常见的应用场景</p>
<table>
<thead>
<tr>
<th align="left">序号</th>
<th align="left">请求方式</th>
</tr>
</thead>
<tbody><tr>
<td align="left">表单请求</td>
<td align="left">默认GET，可以指定 POST</td>
</tr>
<tr>
<td align="left">AJAX请求</td>
<td align="left">默认GET，可以指定 POST</td>
</tr>
<tr>
<td align="left">地址栏请求</td>
<td align="left">GET 请求</td>
</tr>
<tr>
<td align="left">超链接请求</td>
<td align="left">GET 请求</td>
</tr>
<tr>
<td align="left">src资源路径请求</td>
<td align="left">GET 请求</td>
</tr>
</tbody></table>
<p>Get请求：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(method=RequestMethod.GET)</span><br></code></pre></td></tr></table></figure>
<p>Post请求</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(method=RequestMethod.POST)</span><br></code></pre></td></tr></table></figure>

<h2 id="2-2-GET请求"><a href="#2-2-GET请求" class="headerlink" title="2.2 GET请求"></a>2.2 GET请求</h2><p><strong>固定参数1 —— @RequestParam</strong></p>
<p>若请求参数与方法定义的参数名不一致，可使用@RequestParam指定请求域的名称，赋给参，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMappping(&quot;/findByName&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">findUserByName</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(value = &quot;username&quot;)</span> String name)</span>&#123;<br>	System.out.println(name);<br>	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;user&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>也可以用于指定某些参数是否必须传参，若指定为否，不传参数就不会报错，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java">```java<br><span class="hljs-meta">@RequestMappping(&quot;/findByName&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">findUserByName</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(value = &quot;username&quot;, required = false)</span> String name)</span>&#123;<br>	System.out.println(name);<br>	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;user&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>固定参数2——value、method、params</strong><br>可以在@RequestMapping注解内指定请求的类型、路径、参数等，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(value = &quot;/findByName2&quot;,</span><br><span class="hljs-meta">				method = RequestMethod.GET,</span><br><span class="hljs-meta">				params = &quot;username&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">findUserByName2</span><span class="hljs-params">(String username)</span>&#123;<br>	System.out.println(username);<br>	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;user&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>注意这种方式，请求参数必须和方法参数保持一致，否则为空</p>
<h2 id="2-3-POST-表单数据"><a href="#2-3-POST-表单数据" class="headerlink" title="2.3 POST-表单数据"></a>2.3 POST-表单数据</h2><ul>
<li>使用对象接收，该对象对应的POJO类应包含表单name属性的set方法，例如：<br><code>login.html</code><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">&quot;/login&quot;</span> <span class="hljs-attr">method</span>=<span class="hljs-string">&quot;post&quot;</span>&gt;</span><br>	用户名: <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;userName&quot;</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span><br>	密码: <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;password&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;userPassword&quot;</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;submit&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;登陆&quot;</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span><br></code></pre></td></tr></table></figure>
<code>User.java</code><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span>&#123;<br>	<span class="hljs-keyword">private</span> String userName;<br>	<span class="hljs-keyword">private</span> String userPassword;<br>	<span class="hljs-comment">// ...setter getter toString()</span><br>&#125;<br></code></pre></td></tr></table></figure>
<code>Controller.java</code><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(value = &quot;/login&quot;, method=RequestMapping.POST)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">login</span><span class="hljs-params">(User user)</span>&#123;<br>	System.out.println(user.getUserName());<br>	System.out.println(user.getUserPassword());<br>	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;user&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="2-4-视图解析器"><a href="#2-4-视图解析器" class="headerlink" title="2.4 视图解析器"></a>2.4 视图解析器</h2><p>SpringMVC的视图解析器是通过InternalResourceViewResolver对象实现的，一般是在配置文件中定义：</p>
<p>使用案例：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span> = <span class="hljs-string">&quot;prefix&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;/WBE-INF/jsp/&quot;</span>/&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span> = <span class="hljs-string">&quot;suffix&quot;</span> <span class="hljs-attr">value</span> = <span class="hljs-string">&quot;.jsp&quot;</span>/&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h1 id="三、参数传递（Controller-to-View）"><a href="#三、参数传递（Controller-to-View）" class="headerlink" title="三、参数传递（Controller to View）"></a>三、参数传递（Controller to View）</h1><hr>
<h2 id="3-1-方式一：ModelAndView"><a href="#3-1-方式一：ModelAndView" class="headerlink" title="3.1 方式一：ModelAndView"></a>3.1 方式一：ModelAndView</h2><p>如何将模型数据传递给视图？ ModelAndView！</p>
<p>ModelAndView包含视图信息和模型信息，常用方法有：</p>
<ul>
<li>添加模型数据<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java">ModelAndView <span class="hljs-title function_">addObject</span><span class="hljs-params">(String attributeName, Object attributeValue)</span>;<br>ModelAndView <span class="hljs-title function_">addAllObjects</span><span class="hljs-params">(Map&lt;String, ?&gt; modelMap)</span>;<br></code></pre></td></tr></table></figure></li>
<li>设置视图<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">void</span> <span class="hljs-title function_">setView</span><span class="hljs-params">(View view)</span>;<br><span class="hljs-keyword">void</span> <span class="hljs-title function_">setViewName</span><span class="hljs-params">(String viewName)</span>;<br></code></pre></td></tr></table></figure></li>
</ul>
<p>使用案例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/index1&quot;)</span><br><span class="hljs-keyword">public</span> ModelAndView <span class="hljs-title function_">index</span><span class="hljs-params">(String username)</span>&#123;<br>	log.info(<span class="hljs-string">&quot;welcome! username: &quot;</span> + username);<br>	<span class="hljs-type">ModelAndView</span> <span class="hljs-variable">mView</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ModelAndView</span>();<br>	mView.addObject(<span class="hljs-string">&quot;username&quot;</span>, username);<br>	mView.setViewName(<span class="hljs-string">&quot;index&quot;</span>);<br>	<span class="hljs-keyword">return</span> mView;<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="3-2-方式二：Model"><a href="#3-2-方式二：Model" class="headerlink" title="3.2 方式二：Model"></a>3.2 方式二：Model</h2><p>使用案例：<br><code>Controller.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/login2&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">login</span> <span class="hljs-params">(User user, Model model)</span> &#123;<br> 	System.out.println(user.getUserName());<br> 	System.out.println(user.getUserPassword());<br> 	List&lt;User&gt; user = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;&gt;();	<span class="hljs-comment">// 假设users为model数据</span><br> 	<span class="hljs-type">User</span> <span class="hljs-variable">u</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>();<br> 	u.setUserName (user.getUserName());<br> 	u.setUserPassword(user.getUserPassword());<br> 	users.add(u);<br> 	model.addAttrebute(<span class="hljs-string">&quot;users&quot;</span>, users);<br> 	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;user&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p><code>login.jsp</code></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><br>	用户名: $(users.get(0).userName&#125;<br>	密码: $(users.get(0).userPassword&#125;<br><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><br></code></pre></td></tr></table></figure>
<p>好处是：不用显示ModelAndView的构造对象，更加简洁</p>
<h2 id="3-3-方式三：Map"><a href="#3-3-方式三：Map" class="headerlink" title="3.3 方式三：Map"></a>3.3 方式三：Map</h2><p>方式二的Model其实是一个Map的数据结构，现在可用Map作为处理方法传入参数</p>
<p>使用案例：<br><code>Controller.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Requestmapping(&quot;/index3&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">index</span><span class="hljs-params">(String username, Map&lt;String, Object&gt; model)</span>&#123;<br>	log.info(<span class="hljs-string">&quot;hello, SpringMVC! username: &quot;</span> + username);<br>	model.put(<span class="hljs-string">&quot;username&quot;</span>, username);<br>	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;index&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="3-4-使用原生的Servlet"><a href="#3-4-使用原生的Servlet" class="headerlink" title="3.4 使用原生的Servlet"></a>3.4 使用原生的Servlet</h2><p>将 HttpServletRequest对象作为参数传入相应的处理方法即可，使用案例：<br><code>Controller.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RequestMapping(&quot;/session&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">testSession</span><span class="hljs-params">(HttpSession session)</span>&#123;<br>	session.setAttribute(<span class="hljs-string">&quot;username&quot;</span>, <span class="hljs-string">&quot;uni&quot;</span>)<br>	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;user&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<p><code>jsp</code></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><br>	session数据: $&#123;sessionScope.username&#125;<br><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>注：尽管此方法在SpringMVC中不常用来接收请求的参数，但说明了一个很重要的事实：</p>
<ul>
<li>Servlet的原生对象如HttpServletRequest、HttpServletResponse、HttpSession等都可以直接作为控制层方法的参数传入，直接使用即可。</li>
</ul>
<h2 id="3-5-小结"><a href="#3-5-小结" class="headerlink" title="3.5 小结"></a>3.5 小结</h2><p>在SpringMVC框架中，从控制层Controller 到视图层View的参数传递有三种方法，ModelAndView、Model还有Map，推荐使用Model对象，因为它是Spring MVC的标准用法。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/SpringMVC/" class="category-chain-item">SpringMVC</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/SpringMVC/">#SpringMVC</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>SpringMVC 笔记1 框架特点 体系架构 执行流程 参数处理 传递</div>
      <div>http://example.com/2022/01/23/SpringMVC 笔记1 框架特点 _ 体系架构 _ 执行流程 _ 参数处理、传递/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年1月23日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/25/SpringMVC%20%E7%AC%94%E8%AE%B02%20%E6%8E%A7%E5%88%B6%E5%B1%82%E9%87%8D%E5%AE%9A%E5%90%91%E4%B8%8E%E8%AF%B7%E6%B1%82%E8%BD%AC%E5%8F%91%20_%20%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%20_%20SSM%E6%A1%86%E6%9E%B6%E6%95%B4%E5%90%88%E6%A1%88%E4%BE%8B%20_%20%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6%E4%BB%A5%E5%8F%8A%E4%BD%BF%E7%94%A8%20_%20%E5%90%8E%E7%AB%AF%E6%95%B0%E6%8D%AE%E6%A0%A1%E9%AA%8C%E6%9C%BA%E5%88%B6_%20%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E9%97%AE%E9%A2%98/" title="SpringMVC 笔记2 控制层重定向与请求转发 _ 异常处理 _ SSM框架整合案例 _ 分页插件以及使用 _ 后端数据校验机制_ 文件上传问题">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">SpringMVC 笔记2 控制层重定向与请求转发 _ 异常处理 _ SSM框架整合案例 _ 分页插件以及使用 _ 后端数据校验机制_ 文件上传问题</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/01/23/Spring%20%E7%AC%94%E8%AE%B03%20Spring%E6%95%B4%E5%90%88MyBatis%E6%A1%86%E6%9E%B6%20_%20Spring%E5%A3%B0%E6%98%8E%E5%BC%8F%E4%BA%8B%E5%8A%A1%E6%8E%A7%E5%88%B6/" title="Spring 笔记3 Spring整合MyBatis框架 _ Spring声明式事务控制">
                        <span class="hidden-mobile">Spring 笔记3 Spring整合MyBatis框架 _ Spring声明式事务控制</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
